using UnityEditor;
using UnityEngine;

namespace Framework
{
    [CustomPropertyDrawer(typeof(ConditionalAttribute), true)]
    public class ConditionalAttributeDrawer : PropertyDrawer
    {
        private bool _initialized = false;
        private SerializedProperty condProperty;
        private ConditionalAttribute attr;

        private void Init(SerializedObject obj)
        {
            attr = attribute as ConditionalAttribute;
            condProperty = obj.FindProperty(attr.ConditionName);
        }
        
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (!_initialized) Init(property.serializedObject);
            if (attr.ShouldShow(condProperty))
            {
                EditorGUI.PropertyField(position, property, label, true);
            }
            else if (!attr.Hide)
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUI.PropertyField(position, property, label, true);
                EditorGUI.EndDisabledGroup();
            }
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            if (!_initialized) Init(property.serializedObject);
            if (attr.ShouldShow(condProperty) || !attr.Hide)
                return EditorGUI.GetPropertyHeight(property, label, true);
            return 0;
        }
    }
}